package edu.cmu.ece.ds.droidchat;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import edu.cmu.ece.ds.droidchat.controller.UserListBaseAdapter;
import edu.cmu.ece.ds.droidchat.model.ChatSessionInfo;
import edu.cmu.ece.ds.droidchat.model.StringConstants;
import edu.cmu.ece.ds.droidchat.model.UserInfo;
import edu.cmu.ece.ds.droidchat.util.Toolbox;

public class NearbyUsersListActivity extends ListActivity {
    private final static String TAG = "NearbyUsersListActivity";
    private ServiceMessageReceiver mReceiver;
    private ArrayList<UserInfo> mNearbyUserList;
    private ListView mListView;
    private UserListBaseAdapter mUserListBaseAdapter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "---onCreate---");

        // list view
        // prepareNearbyUserList() is for debug only
        mNearbyUserList = prepareNearbyUserList();
        mUserListBaseAdapter = new UserListBaseAdapter(this, mNearbyUserList,
                UserListBaseAdapter.THEME_BLUE);
        setListAdapter(mUserListBaseAdapter);

        mListView = getListView();
        mListView.setTextFilterEnabled(true);
        mListView.setDivider(null);
        // mListView.setFastScrollEnabled(true);
        // mListView.setVerticalFadingEdgeEnabled(false);
        mListView.setCacheColorHint(Color.WHITE);

        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                UserInfo fullObject = (UserInfo) mListView
                        .getItemAtPosition(position);

                /*
                 * Log.d(TAG + " onItemClick()", "position is " + position);
                 * Log.d(TAG + " onItemClick()", "username is " +
                 * fullObject.getUsername()); Log.d(TAG + " onItemClick()",
                 * "ip is " + fullObject.getUserIP());
                 */

                System.out
                        .println("calling addNewOneOnOneChatSessionInfoByUsername "
                                + "Inviter Version in NearbyUserListActivity...");
                String chatSessionId = Toolbox
                        .addNewOneOnOneChatSessionInfoByUsername(fullObject
                                .getUsername());

                // System.out.println("returned chatSessionID=" +
                // chatSessionId);

                ChatSessionInfo chInfo = Toolbox.getChatSession(chatSessionId);

                if (chInfo.isBrandNew()) {
                    Toolbox.createChatWindowActivity(
                            NearbyUsersListActivity.this, true, chatSessionId);
                } else {
                    // we should probably make a TOAST telling the user that the
                    // 1-on-1 chat session has been established, not not open up
                    // the chat window again... the user can open up the chat
                    // session
                    // from ChatSessionListActivity
                    if (chInfo.getUsername() != null) {
                        Toast.makeText(
                                getApplicationContext(),
                                "you have invited \""
                                        + fullObject.getUsername()
                                        + "\" for a 1-on-1 chat session",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(
                                getApplicationContext(),
                                "1-on-1 chat session with \""
                                        + fullObject.getUsername()
                                        + "\" has already been established",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        // broadcast receiver
        mReceiver = new ServiceMessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(StringConstants.ACTION_NEIGHBOR_INFO_MESSAGE);
        this.registerReceiver(mReceiver, filter);
        Log.d(TAG, "ServerMessageReceiver registered! ");
    }

    public void onStart() {
        super.onStart();
        Log.d(TAG, "---onStart---");
    }

    public void onStop() {
        super.onStop();
        Log.d(TAG, "---onStop---");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "---onDestroy---");
        unregisterReceiver(mReceiver);
    }

    // debug only
    private ArrayList<UserInfo> prepareNearbyUserList() {
        return Toolbox.getUserInfoArray();
    }

    private class ServiceMessageReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " + intent);
            String username = intent
                    .getStringExtra(StringConstants.EXTRA_USERNAME);
            String userIp = intent
                    .getStringExtra(StringConstants.EXTRA_USER_IP);

            Log.d(TAG, "onReceive is called");

            mNearbyUserList.clear();
            // mNearbyUserList.addAll(Toolbox.retrieveAllUsers());
            // System.out.println(Toolbox.retrieveAllNeighbors().size());
            mNearbyUserList.addAll(Toolbox.retrieveAllNeighbors());

            // mNearbyUserList.add(Toolbox.retrieveUserInfoByUsername(username));
            mUserListBaseAdapter.notifyDataSetChanged();
        }
    }

}
